package kr.co.doriclassic.chapter18;

import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.DefaultListModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.Serializable;

import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

public class PanelJList extends JPanel implements ActionListener, ListSelectionListener, Serializable {
	private JTextField textField;
	private JTextField tfSelected;
	private JButton btnAdd;
	private JList<String> list;

	public PanelJList() {

		initialize();
	}
	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel paneTop = new JPanel();
		add(paneTop, BorderLayout.NORTH);
		
		textField = new JTextField();
		paneTop.add(textField);
		textField.setColumns(10);
		
		btnAdd = new JButton("추가");
		btnAdd.addActionListener(this);
		paneTop.add(btnAdd);
		
		JPanel panelCenter = new JPanel();
		add(panelCenter, BorderLayout.CENTER);
		
		//동적추가
		list = new JList<String>();
		list.setModel(new DefaultListModel<String>());//문자열만 받음
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		list.addListSelectionListener(this);
		JScrollPane scrollPane = new JScrollPane(list);
		panelCenter.add(scrollPane);
		
		
		JPanel panelBottom = new JPanel();
		add(panelBottom, BorderLayout.SOUTH);
		
		JLabel lblNewLabel = new JLabel("선택된 항목");
		panelBottom.add(lblNewLabel);
		
		tfSelected = new JTextField();
		tfSelected.setEditable(false);
		panelBottom.add(tfSelected);
		tfSelected.setColumns(10);
	}

	
	
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnAdd) {
			actionPerformedBtnAdd(e);
		}
	}
	protected void actionPerformedBtnAdd(ActionEvent e) {
		DefaultListModel<String> model = (DefaultListModel<String>) list.getModel();
		String value = textField.getText().trim();
		model.addElement(value);
		
		textField.setText("");
		textField.requestFocus();
	}
	public void valueChanged(ListSelectionEvent arg0) {
		if (arg0.getSource() == list) {
			valueChangedList(arg0);
		}
	}
	protected void valueChangedList(ListSelectionEvent arg0) {
		tfSelected.setText(list.getSelectedValue());
	}
}
